package servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import ejb.UserFacadeEJBRemote;


/**
 * Servlet implementation class Login
 */
@WebServlet("/Login")
public class Login extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
    @EJB UserFacadeEJBRemote uf; 
	
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Login() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		HttpSession se=request.getSession();
		String user=(String)se.getAttribute("username");
		if(user!=null){
			out.print("You have already login...");
		    response.setHeader("Refresh","1;URL=home.jsp");
		}
		else response.sendRedirect("login.jsp");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String username= request.getParameter("username");
		String password=request.getParameter("password");
		
		boolean check=uf.validate(username, password);
		//boolean valid= login.validateLogin(username, password);
		if(check){
			HttpSession session=request.getSession();
			session.setMaxInactiveInterval(3600);
			session.setAttribute("username", username);
			response.sendRedirect("Home");
		}
		else{
			request.setAttribute("error", "*Username not exist or Password wrong!");
			request.getRequestDispatcher("login.jsp").forward(request, response);
		}
	}

}
